var express = require('express');
var router = express.Router();
const userService = require('../service/userService');
const {sha256,secretKey} = require('../util');
const jwt = require("jsonwebtoken");
/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});
router.post('/usernameExist',async function(req,res){
  // 单一职责
  let {username} = req.body;
  let data = await userService.usernameExist(username);
  if(data.length > 0){
    res.send({
      status:0
    });
  }else{
    res.send({
      status:1
    });
  }
});
router.post('/reg',async function(req,res){
  // post提交获取参数的方法是req.body
  let {username,pwd} = req.body;
  let data = await userService.insert({username,pwd:sha256(pwd)});
  res.send(data);
});
router.post('/login',async function(req,res){
  let {username,pwd} = req.body;
  let data = await userService.login({username,pwd:sha256(pwd)});
  if(data.length > 0){
    // req.session.user = data[0];
    let token = jwt.sign({data:data[0]}, secretKey);
    res.send({
      token,
      status:1
    });
  }else{
    res.send({
      status:0
    });
  }
});

module.exports = router;
